$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'member/userbaseinfo/list',
        datatype: "json",
        colModel: [
            {label: '会员ID', name: 'userId', index: 'member_id', width: 30, align: 'center',key: true},
            {
                label: '会员名', name: 'name', index: 'name', width: 130,
                formatter: function (value, options, row) {
                    var actions = [];
                    actions.push('<a href="javascript:void(0);" onclick="vm.detail(' + row.userId + ');">' + row.name + '</a>');
                    return actions.join(' ');
                }
            },
            {label: '手机号码', name: 'mobile', index: 'mobile', width: 50, align: 'center'},
            {label: '固定电话', name: 'tel', index: 'tel', width: 50, align: 'center'},
            {label: '邮箱', name: 'email', index: 'email', width: 50},
            {
                label: '性别', name: 'sex', index: 'sex', width: 30, align: 'center',
                formatter: function (value, options, row) {
                    return value == 1 ? '男' : '女';
                }
            },
            {
                label: '注册时间',
                name: 'regtime',
                index: 'regtime',
                width: 80,
                formatter: "date",
                formatoptions: {srcformat: 'u', newformat: 'Y-m-d H:i:s'},
                align: 'center'
            },
            {label: '平台来源', name: 'userSource', index: 'user_source', width: 30, align: 'center'},
            {
                label: '用户类型', name: 'userType', index: 'user_type', width: 30,
                formatter: function (value, options, row) {
                    var valueText = "";
                    var userTypeEnum = $("#jqGrid").jqGrid('getGridParam', 'userData').userTypeEnum;
                    $.each(userTypeEnum, function (index, module) {
                        if (module.value == value) {
                            valueText = module.describe;
                        }
                    });
                    return valueText;
                }, align: 'center'
            },
            {label: '会员等级ID', name: 'memberLvId', index: 'member_lv_id', width: 30, align: 'center', hidden: true},
            {label: '会员等级', name: 'memberName', index: 'member_name', width: 30, align: 'center'},
            {label: '经验值', name: 'experience', index: 'experience', width: 30, align: 'center'},
            {label: '预存款', name: 'advance', index: 'advance', width: 30, align: 'center'},
            {label: '积分', name: 'point', index: 'point', width: 30, align: 'center'},
            {label: '信用额', name: 'creditUse', index: 'credit_use', width: 30, align: 'center'},
            {label: '推荐码', name: 'recommendCode', index: 'recommend_code', width: 30, align: 'center'},
            {
                label: '充值', name: 'recharge', index: 'recharge', width: 30, align: 'center',
                formatter: function (value, options, row) {
                    var actions = [];
                    actions.push('<a href="javascript:void(0);" onclick="vm.toMemRecharge(' + row.userId + ');">充值</a>');
                    return actions.join(' ');
                }
            },
            {
                label: '编辑', name: 'edit', index: 'edit', width: 30, align: 'center',
                formatter: function (value, options, row) {
                    var actions = [];
                    actions.push('<a href="javascript:void(0);" onclick="vm.edit(' + row.userId + ');">编辑</a>');
                    return actions.join(' ');
                }
            }
        ],
        viewrecords: true,
        height: 700,
        rowNum: 25,
        rowList: [25, 50, 100],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            //获取枚举参数
            vm.userTypeEnum = $("#jqGrid").jqGrid('getGridParam', 'userData').userTypeEnum;
        }
    });

});

/**
 * 预存款表
 */
function advanceList(userId) {
    $('#jqGrid1').jqGrid('clearGridData');
    $('#jqGrid1').jqGrid('setGridParam', {url: baseURL + 'member/userbaseinfo/advanceList/' + userId}).trigger('reloadGrid');
    $("#jqGrid1").jqGrid({
        url: baseURL + 'member/userbaseinfo/advanceList/' + userId,
        datatype: "json",
        colModel: [
            {label: '交易时间', name: 'mtime', index: 'mtime', width: 150, align: 'center'},
            {label: '业务摘要', name: 'memo', index: 'memo', width: 70, align: 'center'},
            {label: '出入金额', name: 'money', index: 'money', width: 70},
            {label: '当前余额', name: 'memberAdvance', index: 'member_advance', width: 70, align: 'center'},
            {label: '支付方式', name: 'paymethod', index: 'paymethod', width: 70, align: 'center'},
            {label: '支付单号', name: 'paymentId', index: 'payment_id', width: 170, align: 'center'},
            {label: '订单号', name: 'orderId', index: 'order_id', width: 140, align: 'center'},
            {label: '管理备注', name: 'message', index: 'message', width: 150, align: 'center'},
        ],
        caption: "预存款",
        hidegrid: false,
        viewrecords: true,
        height: 200,
        rowNum: 7,
        rowList: [7, 50, 100],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPager1",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid1").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
}

/**
 * 信用支付表
 */
function creditList(userId) {
    $('#jqGrid2').jqGrid('clearGridData');
    $('#jqGrid2').jqGrid('setGridParam', {url: baseURL + 'member/userbaseinfo/creditList/' + userId}).trigger('reloadGrid');
    $("#jqGrid2").jqGrid({
        url: baseURL + 'member/userbaseinfo/creditList/' + userId,
        datatype: "json",
        colModel: [
            {label: '交易时间', name: 'mtime', index: 'mtime', width: 150, align: 'center'},
            {label: '业务摘要', name: 'memo', index: 'memo', width: 150, align: 'center'},
            {label: '出入金额', name: 'money', index: 'money', width: 70},
            {label: '当前余额', name: 'creditUse', index: 'credit_use', width: 70, align: 'center'},
            {label: '支付单号', name: 'paymentId', index: 'payment_id', width: 170, align: 'center'},
            {label: '订单号', name: 'orderId', index: 'order_id', width: 140, align: 'center'},
            {label: '管理备注', name: 'message', index: 'message', width: 150, align: 'center'},
        ],
        caption: "信用支付",
        hidegrid: false,
        viewrecords: true,
        height: 200,
        rowNum: 7,
        rowList: [7, 50, 100],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPager2",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid2").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
}

/**
 * 积分表
 */
function pointList(userId) {
    $('#jqGrid3').jqGrid('clearGridData');
    $('#jqGrid3').jqGrid('setGridParam', {url: baseURL + 'member/userbaseinfo/pointList/' + userId}).trigger('reloadGrid');
    $("#jqGrid3").jqGrid({
        url: baseURL + 'member/userbaseinfo/pointList/' + userId,
        datatype: "json",
        colModel: [
            {label: '添加时间', name: 'addtime', index: 'addtime', width: 150, align: 'center'},
            {label: '业务摘要', name: 'remark', index: 'remark', width: 70, align: 'center'},
            {label: '出入积分', name: 'changePoint', index: 'change_point', width: 70},
            {label: '当前积分', name: 'point', index: 'point', width: 70, align: 'center'},
            {label: '备注', name: 'reason', index: 'reason', width: 70, align: 'center'},
            {label: '支付单号', name: 'paymentId', index: 'payment_id', width: 170, align: 'center'},
            {label: '充值推荐码', name: 'mempayCode', index: 'mempay_code', width: 140, align: 'center'},
            {label: '操作管理员', name: 'operator', index: 'operator', width: 150, align: 'center'},
        ],
        caption: "积分",
        hidegrid: false,
        viewrecords: true,
        height: 200,
        rowNum: 7,
        rowList: [7, 50, 100],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPager3",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid3").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
}

/**
 * 订单表
 */
function orderList(userId) {
    $('#jqGrid4').jqGrid('clearGridData');
    $('#jqGrid4').jqGrid('setGridParam', {url: baseURL + 'member/userbaseinfo/orderList/' + userId}).trigger('reloadGrid');
    $("#jqGrid4").jqGrid({
        url: baseURL + 'member/userbaseinfo/orderList/' + userId,
        datatype: "json",
        colModel: [
            {label: '订单号', name: 'orderId', index: 'order_id', width: 150, align: 'center'},
            {label: '订单状态', name: 'status', index: 'status', width: 70, align: 'center'},
            {label: '支付状态', name: 'payStatus', index: 'pay_status', width: 70},
            {label: '发货状态', name: 'shipStatus', index: 'ship_status', width: 70, align: 'center'},
            {label: '收货人', name: 'shipName', index: 'ship_name', width: 70, align: 'center'},
            {label: '收货电话', name: 'shipTel', index: 'ship_tel', width: 170, align: 'center'},
            {label: '总金额', name: 'payableAmount', index: 'payable_amount', width: 140, align: 'center'},
            {label: '下单日期', name: 'createtime', index: 'createtime', width: 150, align: 'center'},
        ],
        caption: "订单",
        hidegrid: false,
        viewrecords: true,
        height: 200,
        rowNum: 7,
        rowList: [7, 50, 100],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPager4",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid4").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
}

/**
 * 收货地址表
 */
function addressList(userId) {
    $('#jqGrid5').jqGrid('clearGridData');
    $('#jqGrid5').jqGrid('setGridParam', {url: baseURL + 'member/userbaseinfo/addressList/' + userId}).trigger('reloadGrid');
    $("#jqGrid5").jqGrid({
        url: baseURL + 'member/userbaseinfo/addressList/' + userId,
        datatype: "json",
        colModel: [
            {label: '地区', name: 'area', index: 'area', width: 250, align: 'center'},
            {label: '地址', name: 'address', index: 'address', width: 300, align: 'center'},
            {label: '收货人', name: 'name', index: 'name', width: 170, align: 'center'},
            {label: '联系电话', name: 'mobile', index: 'mobile', width: 170, align: 'center'}
        ],
        caption: "收货地址",
        hidegrid: false,
        viewrecords: true,
        height: 200,
        rowNum: 7,
        rowList: [7, 50, 100],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPager5",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid5").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
}

function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes() + ':';
    s = date.getSeconds();
    return Y + M + D + h + m + s;
}


var vm = new Vue({
    el: '#rrapp',
    data: {
        adminUserIdList: [],
        userTypeEnum: [],
        q: {
            username: "",
            mobile: "",
            userType: "",
            beginCreatetime: "",
            endCreatetime: ""
        },
        showList: true,
        showListUpdate: false,
        showDetail: false,
        showMemRecharge: false,
        showAddMem: false,
        title: null,
        userBaseInfo: {},
        mempayType: "",
        payCount: "",
        name: '',
        mobile: '',
        password: '',
        npassword: '',
        rechargeType:'',
        changePwd:false,
        password1:'',
        password2:'',
        checkbtn:false,
        loading:false,
        options: [],
        loading: false,
        list: [],
        states: [],
    },
    mounted() {
        //获取所属客服adminUserIdList
        $.get(baseURL + "member/userbaseinfo/adminUserIdList", function (r) {
            vm.states = r.adminUserIdList;
            vm.list = vm.states.map(item => {
                return {value: item.userId, label: item.username};
            });
        });
    },
    methods: {
        checkBeginDate: function () {
            WdatePicker({
                dateFmt: 'yyyy-MM-dd', isShowClear: false, onpicking: function (dp) {
                    vm.q.beginCreatetime = dp.cal.getNewDateStr();
                }
            })
        },
        checkEndDate: function () {
            WdatePicker({
                dateFmt: 'yyyy-MM-dd', isShowClear: false, onpicking: function (dp) {
                    vm.q.endCreatetime = dp.cal.getNewDateStr();
                }
            })
        },
        reset: function (event) {
            vm.q.username = ''
            vm.q.mobile = ''
            vm.q.userType = ''
            vm.q.beginCreatetime = ''
            vm.q.endCreatetime = ''
            vm.reload()
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false
            vm.showListUpdate = false
             vm.showDetail = false
            vm.showAddMem = true
            vm.title = "会员新增"
            vm.name = ''
            vm.password = ''
            vm.npassword = ''
            vm.mobile = ''
        },
        //会员编辑
        edit: function (userId) {
            vm.showList = false
            vm.showListUpdate = true
            vm.showDetail = false
            vm.showAddMem = false
            vm.title = "会员编辑"
            vm.getInfo(userId)
        },
        //会员充值
        toMemRecharge: function (userId) {
            vm.showList = false
            vm.showListUpdate = false
            vm.showDetail = false
            vm.showMemRecharge = true
            vm.showAddMem = false
            vm.title = "会员充值"
            vm.rechargeType='advance'
            vm.getInfo(userId)
        },
        //会员详情
        detail: function (userId) {
            vm.showList = false
            vm.showListUpdate = false
            vm.showDetail = true
            vm.showAddMem = false
            vm.title = "会员详情"
            vm.getInfo(userId)
            advanceList(userId)
            creditList(userId)
            pointList(userId)
            orderList(userId)
            addressList(userId)
        },
        update: function (event) {
            var url = "member/userbaseinfo/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                dataType: "json",
                data: $("#userInfoForm").serialize(),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        //删除会员
        del: function (event) {
            var userIds = getSelectedRows();
            if (userIds == null) {
                return;
            }
            var str = '';
            for (var i = 0; i < userIds.length; i++) {
                var rowData = $("#jqGrid").jqGrid("getRowData", userIds[i]);
                str += rowData.userId + ",";
            }

            /*
                  var nos=[];
                  $.each(userIds, function(i,val){
                      //遍历templateIds获取当前选中的一行的字段
                      var rowData = $("#jqGrid").jqGrid('getRowData',val);
                      //根据一行字段的对象获得其中的属性
                      console.info(rowData)
                      nos.push(rowData.userId)
                  });*/

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: baseURL + "member/userbaseinfo/delete",
                    data: {'ids': str},
                    // data: JSON.stringify(nos),
                    success: function (r) {
                        if (r.code > 0) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (userId) {
            $.get(baseURL + "member/userbaseinfo/info/" + userId, function (r) {
                vm.userBaseInfo = r.userBaseInfo;
            });
            //获取所属客服adminUserIdList
            $.get(baseURL + "member/userbaseinfo/adminUserIdList", function (r) {
                vm.adminUserIdList = r.adminUserIdList;
            });
        },
        reload: function (event) {
            vm.showList = true
            vm.showListUpdate = false
            vm.showDetail = false
            vm.showMemRecharge = false
            vm.showAddMem = false
            var page = $("#jqGrid").jqGrid('getGridParam', 'page')
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {//postData此数组内容直接赋值到url上，参数类型：{name1:value1…}
                    'username': vm.q.username.trim(),
                    'mobile': vm.q.mobile.trim(),
                    'userType': vm.q.userType,
                    'beginCreatetime': vm.q.beginCreatetime,
                    'endCreatetime': vm.q.endCreatetime
                },
                page: 1
            }).trigger("reloadGrid");
        },
        close: function (event) {
            vm.showList = true
            vm.showListUpdate = false
            vm.showDetail = false
            vm.showMemRecharge = false
            vm.showAddMem = false
        },
        //会员收货地址
        getShipAddr: function (userId) {
            $.get(baseURL + "member/userbaseinfo/getShipAddr/" + userId, function (r) {
                vm.shipAddr = r.shipAddr;
            });
        },
        //会员充值
        memRecharge: function (event) {
            var rechargeCount = $.trim($('#rechargeCount').val());
            if (!rechargeCount) {
                alert("请输入充值金额")
                return false;
            }
            //当前信用额+充值金额,不能大于信用额度
            // if (vm.rechargeType=='creditUse'&&(vm.userBaseInfo.creditUse+rechargeCount>vm.userBaseInfo.creditLimit)) {
            //     alert('不能超过信用额度!')
            //     return
            // }

            $.ajax({
                type: "POST",
                url: baseURL + "member/userbaseinfo/memRecharge",
                dataType: "json",
                data: $("#mempayForm").serialize(),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        //新增会员
        addMem: function () {
            if (!vm.name) {
                alert("请输入会员名")
                return
            }
            if (!vm.password) {
                alert("请输入密码")
                return
            }
            if (!vm.npassword) {
                alert("请输入确认密码")
                return
            }
            if (vm.password != vm.npassword) {
                alert("密码输入不一致")
                return
            }

            if (vm.mobile&&!isPoneAvailable(vm.mobile)) {
                alert("请检查手机号码")
                return
            }
            vm.checkbtn=true
            vm.loading=true
            $.ajax({
                type: "POST",
                url: baseURL + "member/userbaseinfo/addMem",
                dataType: "json",
                data: $("#addMemForm").serialize(),
                success: function (r) {
                    if (r.code == 0) {
                        alert('操作成功', function (index) {
                            vm.reload()
                            vm.checkbtn=false
                            vm.loading=false
                        });
                    } else {
                        vm.checkbtn=false
                        vm.loading=false
                        alert(r.msg)
                    }
                }
            });
        },
        //修改密码按钮
        changePassword() {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
        vm.changePwd=true
        },
        //重置密码
        resetPassword: function () {
            var userId = getSelectedRow();
            if (vm.password1 != vm.password2) {
                alert('两次输入的密码不一致!')
                return
            }
            $.ajax({
                type: "POST",
                url: baseURL + "member/userbaseinfo/resetPassword",
                dataType: "json",
                data: {"userId": userId,"password":vm.password1},
                success: function (r) {
                    if (r.code == 0) {
                        alert('操作成功', function (index) {
                            vm.reload()
                        });
                    } else {
                        alert(r.msg)
                    }
                }
            });
        },
        remoteMethod(query) {
            if (query !== '') {
                vm.loading = true;
                setTimeout(() => {
                    vm.loading = false;
                    vm.options = vm.list.filter(item => {
                        return item.label.indexOf(query) > -1;
                    });
                }, 200);
            } else {
                vm.options = [];
            }
        }
    }
});

//手机号码正则
function isPoneAvailable(str) {
    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (!myreg.test(str)) {
        return false;
    } else {
        return true;
    }
}